const fs = require('fs')
const path = require('path')
const config = require('./config')
const { readFile, urlParamsProcess, runShell, uuid } = require('./util')

let myConfigPath = path.resolve(__dirname, './myConfig.json')
let myConfig = {}
if (fs.existsSync(myConfigPath)) {
    myConfig = Object.assign(myConfig, readFile(myConfigPath, true))
}

const htmlRoute = async (req, res) => {

    const appJsonPath = path.resolve((myConfig.distPath || config.distPath), 'app.json')
    let appJson = Object.assign({}, await readFile(appJsonPath, true))

    const htmlTemplatePath = path.resolve(__dirname, './index.html')
    let htmlTemplate = await readFile(htmlTemplatePath)
    htmlTemplate = htmlTemplate.replace('#default-cliPath#', myConfig.cliPath || config.cliPath)
    htmlTemplate = htmlTemplate.replace('#default-postUrl#', myConfig.postUrl || config.postUrl)
    htmlTemplate = htmlTemplate.replace('#default-distPath#', myConfig.distPath || config.distPath)

    if(appJson && appJson.pages && Array.isArray(appJson.pages)) {
        htmlTemplate = htmlTemplate.replace('#pageList#', JSON.stringify(appJson.pages || []))
    }

    res.setHeader('Content-Type', 'text/html')
    res.body = htmlTemplate
}

const apiRoute = async (req, res) => {
    const paramStr = await new Promise((reslove) => {
        let body = ''
        req.on('data', (chunk) => {
            body += chunk
        })

        req.on('end', () => {
            reslove(body.toString())
        })
    })

    const paramJson = urlParamsProcess(paramStr)
    const fileName = uuid() + '.txt'
    const qrcodePath = path.resolve(__dirname, './qrcode/' + fileName)

    let shellParam = [
        '--preview',
        paramJson.distPath,
        '--preview-qr-output',
        `base64@${qrcodePath}`
    ]

    if (paramJson.pathName) {
        shellParam.push('--compile-condition')
        let tmp = '{"pathName":"' + paramJson.pathName + '"'
        if (paramJson.query) {
            tmp += ',"query":"' + paramJson.query + '"'
        }
        tmp += '}'
        shellParam.push(tmp)
    }

    await runShell('/Applications/wechatwebdevtools.app/Contents/MacOS/cli', [...shellParam], true)

    const base64Str = await readFile(qrcodePath)

    res.body = 'data:image/png;base64,' + base64Str
}

const imgRoute = async (req, res) => {
    const qrcodePath = path.resolve(__dirname, './qrcode' + req.url)
    const base64Str = await readFile(qrcodePath)
    res.setHeader('Content-Type', 'image/png')
    res.body = base64Str
}

const errorRoute = async (req, res) => {
    res.body = '<h2>page not found</h2>'
}

const routeMap = {
    '/': htmlRoute,
    '/index.html': htmlRoute,
    '/api': apiRoute,
}

module.exports = async (req, res) => {
    const url = req.url
    if (url && routeMap[url]) {
        await routeMap[url](req, res)
    }
    else if (/(\/)?[\w\d-]\.txt/i.test(url)) {
        await imgRoute(req, res)
    }
    else {
        await errorRoute(req, res)
    }
}